<template>
  <div class="roleManager">
    <CommonBtn  label-name="系统角色信息" v-if="!button || (button.event!='allotAuthority()' && button.event!='detail()')" :buttons="buttons" @onButtonClick="onButtonClick">
    </CommonBtn>
    <CommonList ref="list"  :buttons="buttons" v-if="!button || (button.event!='allotAuthority()' && button.event!='detail()')"
                :columns="columns" :listUrl="listUrl" @tableSelect="tableSelect" row-key="rolesId" @dbClick="openItem"></CommonList>
    <EnsurePopUp :out-btn="button" @close="button=null" @refresh="refresh" :original-data="row"
                 :delete-url="$api.API_ROLESMANAGEMENT_DELETE"></EnsurePopUp>

    <el-dialog :title="'系统角色信息-'+(button?(button.event=='add()'?'添加':'编辑'):'')" :visible.sync="show" width="40%">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="基本信息" name="first">
          <el-form :model="submit" status-icon :label-width="'80px'" ref="form">
            <el-form-item :label="item.name" :key="index" :prop="item.prop"  v-for="(item,index) of addItems" :rules="item.required?{ required: true, message: '不能为空', trigger: 'blur' }:null">
              <el-select v-if="item.type=='select'" v-model="submit[item.prop]" placeholder="请选择">
                <el-option v-for="(item,index) of item.options" :label="item.rolesName" :value="item.rolesId" :key="index"></el-option>
              </el-select>
              <el-input  v-if="item.type=='text' || item.type=='textarea'" autocomplete="off" v-model="submit[item.prop]" :type="item.type"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="角色成员" name="second">
          <el-row>
            <el-col :span="12" style="border: 1px solid #eee;height: 300px">
              <div class="main-label">
                <div>所有成员</div>
              </div>
              <el-tree :data="roleData" :props="{ label: 'organizationName',children:'children'}"  :expand-on-click-node="false"  check-strictly
                       highlight-current default-expand-all node-key="organizationId" style="height: 270px;overflow: scroll">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span><i v-if="data.isUser == '1'" class="el-icon-user"></i><i v-else class="el-icon-tickets"></i>{{ node.label }}</span>
                   <span v-if="data.isUser == '1'">
                    <el-button
                      type="text"
                      size="mini"
                      @click="() => addUser(data)">
                      添加
                    </el-button>
                   </span>
                 </span>
              </el-tree>
            </el-col>
            <el-col :span="12" style="border: 1px solid #eee;height: 300px">
              <div class="main-label">
                <div>已选成员</div>
              </div>
              <el-table :data="selectedUser" height="270" border stripe>
                <el-table-column label="用户名" prop="organizationName"></el-table-column>
                <el-table-column label="所属部门" prop="departmentName"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      @click="() => removeUser(scope.row)">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <div v-if="button && (button.event=='allotAuthority()' || button.event=='detail()')">
      <CommonBtn :label-name="'所属角色【'+row.rolesName+'】'" >
        <div slot="appendCondition" :class="{'tab':true,'on':activeIndex==1}" @click="activeIndex=1"v-if="button && button.event=='detail()'">角色权限</div>
        <div slot="appendCondition" :class="{'tab':true,'on':activeIndex==2}" @click="activeIndex=2" v-if="button && button.event=='detail()'">角色成员</div>
        <div slot="appendCondition" style="display: inline-block;float:right;margin-right: 20px">
          <el-button  @click="button = null">返回</el-button>
        </div>
      </CommonBtn>
      <el-table :data="menuList" border stripe :tree-props="{children: 'subMenuList'}" row-key="menuId" default-expand-all>
        <el-table-column label="URL菜单权限" prop="menuName" width="200"></el-table-column>
        <el-table-column label="图标" prop="menu" width="55"></el-table-column>
        <el-table-column label="权限" width="55">
          <template slot-scope="scope">
            <el-checkbox :checked="selectedMenu.indexOf(scope.row.menuId)>-1" @change="((pre, next) => {checkChange(pre, next, scope.row.menuId)})" :disabled="button && button.event=='detail()'"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="操作按钮权限">item
          <template slot-scope="scope">
            <div v-for="item of scope.row.buttonMenuList" :key="item.menuId" style="display: inline-block;margin-right: 10px">
              <el-checkbox style="margin-right:5px" :checked="selectedMenu.indexOf(item.menuId)>-1" @change="((pre, next) => {checkChange(pre, next, item.menuId)})" :disabled="button && button.event=='detail()'"></el-checkbox><span>{{item.menuName}}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
    import CommonList from "../../common/CommonList";
    import CommonBtn from "../../common/CommonBtn";
    import CommonEdit from "../../common/CommonEdit";
    import EnsurePopUp from "../../common/EnsurePopUp";
    export default {
        name:'roleManager',
        data(){
            return{
                buttons:[
                    this.$config.BTNS.ADD,
                    this.$config.BTNS.EDIT,
                    this.$config.BTNS.DELETE,
                    this.$config.BTNS.ALLOTAUTHORITY,
                    this.$config.BTNS.DETAIL,
                ],
                columns:[
                    {
                        prop:'rolesName',
                        label:'角色名称'
                    },
                    {
                        prop:'sortCode',
                        label:'显示顺序'
                    },
                    {
                        prop:'createUserName',
                        label:'创建用户'
                    },
                    {
                        prop:'createDate',
                        label:'创建时间'
                    },
                    {
                        prop:'modifyUserName',
                        label:'修改用户'
                    },
                    {
                        prop:'modifyDate',
                        label:'修改时间'
                    },
                    {
                        prop:'rolesRemark',
                        label:'角色描述'
                    }
                ],
                listUrl:this.$api.API_ROLESMANAGEMENT_LIST,
                //新增有下拉框
                button:null,
                row:{},
                show:false,
                activeName:'first',
                submit:{},
                addItems:[
                    {name:'角色名称',prop:'rolesName',type:'text',required:true},
                    {name:'节点位置',prop:'parentId',type:'select',required:true},
                    {name:'显示顺序',prop:'sortCode',type:'text',required:true},
                    {name:'备注描述',prop:'rolesRemark',type:'textarea'},
                ],
                roleData:[],
                selectedUser:[],
                menuList:[],
                selectedMenu:[],
                activeIndex:'1'
            }
        },
        methods:{
            onButtonClick(item) {
                if (item.event == 'edit()'|| item.event == 'Delete()' || item.event == 'allotAuthority()' || item.event == 'detail()') {
                    if (!this.row || JSON.stringify(this.row) == '{}') {
                        this.$message.error("请选择一行数据")
                        return
                    }
                }
                if (item.event == 'add()') {
                    this.row = {}
                    this.submit = {}
                    this.show = true
                    this.selectedUser = []
                }

                if (item.event == 'edit()') {
                    this.show = true
                    this.initData()
                }

                if (item.event == 'allotAuthority()') {
                    this.getSysMenuInfo()
                }

                if (item.event == 'detail()') {
                    this.getSysMenuInfo()
                }

                this.button = item
            },
            editBack(item) {
                this.button = item
            },
            tableSelect(row) {
                this.row = row
                this.submit = row
            },
            openItem(item) {
                this.button = this.$config.BTNS.DETAIL
                this.getSysMenuInfo()
            },
            handleSelect(key, keyPath) {
            },
            initData() {
                let params;
                if (this.row && JSON.stringify(this.row)!='{}'){
                    params = {rolesId:this.row.rolesId}
                }
                this.$http.get(this.$api.API_ROLESMANAGEMENT_INIT,params).then(resp=>{
                    let node = [{rolesName:'角色信息-父节',rolesId:'0'}]
                    node = node.concat(resp.nodeList)
                    this.addItems[1].options = node
                    this.roleData = this.setRoleData(resp.rolesList)
                    this.selectedUser = resp.existMembers
                })
            },
            setRoleData(rolesList) {
                for (let i=0;i<rolesList.length;i++) {
                    if (rolesList[i].userList && rolesList[i].userList.length>0) {
                        rolesList[i].children = rolesList[i].children.concat(rolesList[i].userList)
                    }
                    if (rolesList[i].children && rolesList[i].children.length>0) {
                        this.setRoleData(rolesList[i].children)
                    }
                }
                return rolesList
            },
            refresh() {
                this.$refs.list.search()
            },
            addUser(item) {
                for (let i=0;i<this.selectedUser.length;i++) {
                    if (item.organizationId == this.selectedUser[i].organizationId){
                        this.$message.error('该用户已添加')
                        return
                    }
                }
                this.selectedUser.push(item)
            },
            removeUser(item) {
                for (let i=0;i<this.selectedUser.length;i++) {
                    if (this.selectedUser[i].organizationId == item.organizationId) {
                        this.selectedUser.splice(i,1)
                        return
                    }
                }
            },
            handleSubmit() {
                this.$refs.form.validate((valid) => {
                    if (!valid) {
                        this.$message.error('缺少字段！')
                        return false;
                    }
                });
                let userIds = this.selectedUser.map((item)=>{return item.organizationId})
                this.submit.userIds = userIds.join(',')
                let url = this.button == this.$config.BTNS.ADD?this.$api.API_ROLESMANAGEMENT_ADD:this.$api.API_ROLESMANAGEMENT_UPDATE
                this.$http.post(url,this.submit).then(resp=>{
                    this.$message.success('操作成功！')
                    this.show = false
                    this.refresh()
                },msg=>{})
            },
            getSysMenuInfo() {
                this.$http.get(this.$api.API_ROLESMANAGEMENT_AUTHORITY,{rolesId:this.row.rolesId}).then(resp=>{
                    this.menuList = resp.menuList
                    this.selectedMenu = resp.selectedMenuIdList
                },msg=>{})
            },
            checkChange(pre,next,item) {
                if (pre) {
                    if (this.selectedMenu.indexOf(item)<0) {
                        this.selectedMenu.push(item)
                    }
                } else {
                    if (this.selectedMenu.indexOf(item)>-1){
                        this.selectedMenu.splice(this.selectedMenu.indexOf(item), 1);
                    }
                }
                let params = {rolesId:this.row.rolesId,menuIds:this.selectedMenu.join(',')}
                this.$http.post(this.$api.API_ROLESMANAGEMENT_SAVE,params).then(resp=>{
                    this.$message.success('操作成功！')
                },msg=>{})
            }
        },
        created(){
            this.initData()
        },
        getSysMenuInfo() {
            this.$http.get(this.$api.API_USER_GROUP_SYS_MENU_INFO,{userGroupId:this.row.rolesId}).then(resp=>{
                this.menuList = resp.sysMenuList
                this.selectedMenu = resp.selectedMenuIdList
            },msg=>{})
        },
        components:{CommonList,CommonBtn,CommonEdit,EnsurePopUp}
    }
</script>

<style lang="less" scoped>
  /deep/.el-dialog__header{
    padding: 10px;
    background: #d51900;
  }
  /deep/.el-dialog__headerbtn{
    top:10px;
    right:10px;
    i{
      color: white !important;
    }
  }

  /deep/.el-form-item__label,/deep/.el-form-item__content{
    line-height: unset;
    font-size: 9pt;
    color: black;
  }

  /deep/.el-dialog__title{
    color: white;
    font-size: 14px;
    font-weight: bold;
  }

  /deep/.el-dialog__body{
    padding: 10px 20px;
  }

  /deep/.el-input__inner{
    height: 24px;
    line-height: 24px;
    border-radius: 0;
  }

  .el-form-item {
    margin-bottom: 15px;
  }

  /deep/.el-input__icon{
    line-height: 25px;
  }

  /deep/.el-form-item__error{
    padding: 0px;
  }

  .main-label{
    border: #ccc 1px solid;
    border-bottom: 0;
    background-image: url(../../../assets/img/datagrid_header_bg.gif);
    background-repeat: repeat-x;
    height: 27px;
    line-height: 27px;
    font-weight: bold;
    padding-left: 5px;
  }

  .tab{
    display: inline-block;
    padding: 0 20px;
    border: 1px solid #cccccc;
    border-bottom: none;
    border-top: none;
    cursor: pointer;
    &.on{
      color: #3a8ee6;
    }
  }

  /deep/.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after{
    border-color: #000;
  }


</style>


